package com.usts.edu.stack;

/**
 * Created by Guanzhong Hu
 * Date :2019/12/28
 * Description : 栈的实现
 * Version :1.0
 */
public class SqlStack implements IStack {

    private Object[] stackElem; //对象数组

    private int top;// 在非空栈时，top始终指向栈顶元素的下一个存储位置，当栈空时，top = 0

    public SqlStack(int maxSize) {
        top = 0;
        stackElem = new Object[maxSize];
    }

    @Override
    public void clear() {
        top = 0;
    }

    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    @Override
    public int length() {
        return top;
    }

    @Override
    public Object peek() {
        if (!isEmpty()) {
            return stackElem[top - 1];
        } else {
            return null;
        }
    }

    @Override
    public void push(Object x) throws Exception {
        if (top == stackElem.length) throw new Exception("栈内元素已满");
        stackElem[top] = x;
        top++;
    }

    @Override
    public Object pop() {
        if (isEmpty())
            return null;
        else 
            return stackElem[--top];
    }

    @Override
    public void display() {
        for (int i = top-1; i >=0; i--) {
            System.out.println(stackElem[i].toString()+"");
        }
    }

}
